import React, { Component } from "react";
import { SideBar } from "antd-mobile";
import { getFirstCategoryListApi } from "@/api/goods";
import myPubSub from "@/utils/myPubSub";

export default class FirstList extends Component {
  state = {
    tabs: [],
    activeKey: "",
  };

  componentDidMount() {
    console.log("父组件：componentDidMount");
    this.getFirstCategoryList();
  }

  // 获取第一级的分类
  async getFirstCategoryList() {
    let res = await getFirstCategoryListApi();
    if (res.data.code === 200) {
      this.setState(
        {
          tabs: res.data.list,
          activeKey: res.data.list[0].id,
        },
        () => {
          console.log("父级的publish");
          myPubSub.publish("chuanFirstId", this.state.activeKey);
        }
      );
    }
  }

  changeActiveKey = (activeKey) => {
    this.setState(
      {
        activeKey: activeKey,
      },
      () => {
        myPubSub.publish("chuanFirstId", activeKey);
      }
    );
  };

  render() {
    return (
      <SideBar
        activeKey={String(this.state.activeKey)}
        onChange={this.changeActiveKey}
      >
        {this.state.tabs.map((item) => (
          <SideBar.Item key={item.id} title={item.name} />
        ))}
      </SideBar>
    );
  }
}
